package org.exez.modules.visitor.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.util.UUID;

/**
 * @description: 传入图片的base64
 * @author: KimJun
 * @date: 18/11/13 00:25
 */
public class Base64Util {

    public static MultipartFile base64ToMultipart(String base64) {
        try {

            BASE64Decoder decoder = new BASE64Decoder();
            byte[] b = new byte[0];
            b= decoder.decodeBuffer(base64);
            /*if (baseStrs.length>1) {
                b = decoder.decodeBuffer(baseStrs[0]);
            }else {
                b = decoder.decodeBuffer(baseStrs[1]);
            }*/

            for(int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            return new BASE64DecodedMultipartFile(b, base64);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String upload(MultipartFile file,String fileRootPath){
        String filePath = "";

        // 上传简单文件名
        String originalFilename = file.getOriginalFilename();
        System.out.println(originalFilename);
        String[] split = originalFilename.split("\\.");

        String hz = split[split.length - 1];
        // 存储路径
        filePath = new StringBuilder(fileRootPath)
                .append(UUID.randomUUID().toString().replaceAll("-", ""))
                .append(".")
                .append(hz)
                .toString();
        try {
            // 保存文件
            file.transferTo(new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return filePath.replace(fileRootPath, "");

    }

    //测试
    public static void main(String[] args) {
        MultipartFile multipartFiles[] = new MultipartFile[2];
        multipartFiles[0] = Base64Util.base64ToMultipart("");
        System.out.println(multipartFiles[0].getSize());

    }
}
